package com.scmt.hmzd.wxLoginUtils;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.google.gson.Gson;
import com.scmt.core.common.constant.SecurityConstant;
import com.scmt.core.common.exception.ScmtException;
import com.scmt.core.common.redis.RedisTemplateHelper;
import com.scmt.core.common.vo.TokenMember;
import com.scmt.core.config.properties.ScmtAppTokenProperties;
import com.scmt.hmzd.entity.HmWxUser;
import com.scmt.hmzd.service.IHmWxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class WxSecurityUtil {
    @Autowired
    private IHmWxUserService iHmWxUserService;

    @Autowired
    private ScmtAppTokenProperties appTokenProperties;

    @Autowired
    private RedisTemplateHelper redisTemplate;


    public String getWxUserToken(String openid, int platform) {
        if (StrUtil.isBlank(openid)) {
            throw new ScmtException("openid不能为空");
        }
        // 生成token
        String token = IdUtil.simpleUUID();
        TokenMember member = new TokenMember(openid, platform);
        String key = SecurityConstant.MEMBER_TOKEN + member.getUsername() + ":" + platform;
        // 单平台登录 之前的token失效
        if (appTokenProperties.getSpl()) {
            String oldToken = redisTemplate.get(key);
            if (StrUtil.isNotBlank(oldToken)) {
                redisTemplate.delete(SecurityConstant.TOKEN_MEMBER_PRE + oldToken);
            }
        }
        redisTemplate.set(key, token, appTokenProperties.getTokenExpireTime(), TimeUnit.DAYS);
        redisTemplate.set(SecurityConstant.TOKEN_MEMBER_PRE + token, new Gson().toJson(member), appTokenProperties.getTokenExpireTime(), TimeUnit.DAYS);
        return token;
    }


    public HmWxUser getCurrentWxUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated() || authentication.getName() == null
                || authentication instanceof AnonymousAuthenticationToken) {
            throw new ScmtException("未检测到登录信息");
        }
        return iHmWxUserService.findByOpenid(authentication.getName());
    }
}
